<!--
PAGE DOCUMENTATION:
==================
The user is redirected here to perform the sending operation.
Here he will choose the recipients of his message

Parameters that can be sent to this page:
----------------------------------------
new - an indicator if the sent message a newly recorded one 
		(user redirected here after recording) or not (user chose an existing message to send).
		Values: 0 (not new) or 1 (new).
message_name - (only if new=1) - the name of the new message.	
newFileName - (only if new=1) - the filename of new message (no extention).
recipient - if the user got to this page after asking to respond a received message. 
			Value: friend's facebook user ID.
index - (only if new=0) - Value: the DB index of the message sent.
cancel - if the user chose to cancel sending.
noApp - if the user sent the messag (also) to friends that don't have the appliction.
		Value: a list with their FB user IDs.

-->

<fb:js-string var="dialog_fbml">  
    <div id="dialog_content">  
        <div class="dialog_loading">Please Wait...</div>  
    </div>  
</fb:js-string> 

<?php

	require_once 'appinclude.php';
?>
<script>
function doAjax(message_index)
{
    var dialog = new Dialog().showMessage("Sending", dialog_fbml,"Cancel");
	var ajax = new Ajax();
    ajax.responseType = Ajax.FBML;
    ajax.ondone = function(data)
    {
    	document.getElementById('dialog_content').setInnerFBML(data);
    };
    ajax.requireLogin = 1;
    ajax.post('<?php echo SERVER; ?>/sendProcess.php', {ids: getSelectedUsers(),send: 1, index: message_index});
}

</script>
<?php
	require_once 'sqlLib.php';
	require_once 'logsLib.php';
	require_once 'generalLib.php';
	require_once 'multiFriendsSelector.php';
	
	$currentPage = 'send';
	date_default_timezone_set("UTC");
	$user_id = $facebook->user;
	$sqlDb = new mysqli("localhost", "root", "", "messages");
	$sqlDb->query('SET NAMES utf8');
	
	/* check connection */
	if (mysqli_connect_errno()) {
    	documentError($user_id,$currentPage,"Connect to MYSQL failed: ".mysqli_connect_error());
    	printErrorMsg("connecting to the database");
	} else {
		logMysqliConnectionOpened($user_id,$currentPage);
		if (isset($_POST['newMsg'])) {
			/* user just chose/recorded a message to send */
			if (($new=($_POST['newMsg']))==1) {
				/* it'a a new msg  - enter new row to DB */
				if (!isset($_REQUEST['message_name']) || !isset($_REQUEST['newFileName']) || !isset($_REQUEST['recipient'])) { 
					documentError($user_id,$currentPage,'Not enough parameters for page send.php: message_name:'.$_REQUEST['message_name'].' , newFileName:'.$_REQUEST['newFileName'].', recipient:'.$_REQUEST['recipient']);
					$sqlDb->close();
					logMysqliConnectionClosed($user_id,$currentPage);
					logRedirection($user_id, "error.php?action=send",$currentPage);
					echo "<fb:redirect url=\"error.php?action=send\" />";
				} else {
					/* get parameters */
					$message_name = htmlentities(urldecode($_REQUEST['message_name']),null,'UTF-8');
					$filename = $_REQUEST['newFileName'].".flv";
					$recipient = $_REQUEST['recipient'];
					/* put new msg line in DB (of recorded message) */
					if (!($index = enterNewMsgRow($sqlDb,$message_name,$user_id,0,$filename)))
					{
						documentError($user_id,$currentPage,"enterNewMsgRow failed: message_name: ".$message_name.", user_id: ".$user_id.", filename: ".$filename);
						/* delete file */
						$fullFileName = $filesLocation .$filename;
						$unlinkRes = unlink($fullFileName);
						logFunctionCall($user_id,'unlink',$fullFileName,$unlinkRes,$currentPage);
						$sqlDb->close();
						logMysqliConnectionClosed($user_id,$currentPage);
						logRedirection($user_id, "error.php?action=send",$currentPage);
 						echo "<fb:redirect url=\"error.php?action=send\" />";
					} else {
						logFunctionCall($user_id, 'enterNewMsgRow - original', "sqlDb,".$message_name.','.$user_id.',0,'.$filename,$index,$currentPage);
						echo "<div align=\"center\">&nbsp;</div>
								<fb:explanation>
     							<fb:message>Your message was recorded and saved.</fb:message>
     							In case you want to delete it, you can do it from your recorded messages table.
								</fb:explanation>";
					}
				}
			} else { 
				/* it's an old msg - no need to create new DB entry, get message name */
				if (!isset($_REQUEST['index']) || !isset($_REQUEST['recipient'])) {			
					documentError($user_id,$currentPage,"Not enough parameters for page send.php:  index:".$_REQUEST['index'].", recipient:".$_REQUEST['recipient']);
					$sqlDb->close();
					logMysqliConnectionClosed($user_id,$currentPage);
					logRedirection($user_id, "error.php?action=send",$currentPage);
					echo "<fb:redirect url=\"error.php?action=send\" />";
				} else {
					/* get parameters */
					$index = $_REQUEST['index'];
					$recipient = $_REQUEST['recipient'];
					if (($message_name = getColumnData($sqlDb,"messages_data",$index,'message_name'))==-13)
					{
						documentError($user_id,$currentPage,"getColumnData failed:  index: ".$index.", column: message_name.");
						$sqlDb->close();
						logMysqliConnectionClosed($user_id,$currentPage);
						logRedirection($user_id, "error.php?action=send",$currentPage);
						echo "<fb:redirect url=\"error.php?action=send\" />";
					} else {
						logFunctionCall($user_id, 'getColumnData', "sqlDb,messages_data,".$index.",message_name", $message_name,$currentPage);				
					}
				}
			}
		} else {
			/* an action was made on this page */
			if (isset($_REQUEST['cancel'])) {
				/* user pressed the cancel button*/
				$sqlDb->close();
				logMysqliConnectionClosed($user_id,$currentPage);
				logRedirection($user_id, "sendMessage.php",$currentPage);
				echo "<fb:redirect url=\"sendMessage.php\" />";
			} else {
				$recipientsWithOut = $_REQUEST['noApp'];
//				$failList = $_REQUEST['fail'];
				if (!(inviteRecipients($recipientsWithOut, $user_id, $facebook))) {
					documentError($user_id,$currentPage,"inviteRecipients failed - user_id: $user_id, friends: $recipientsWithOut");
				} 
				exit();
				}
			}
		}	
		/* show page content: */
		echo "<table cellpadding=\"10\" align=\"center\">
			<tr><td align=\"center\">
			</td></tr>
			<tr><td>
			<h1 align=\"center\" style=\"color:#0e1f5b\"> <font size=\"4\">Choose some of your friends to enjoy \"$message_name\".</font></h1>
			</td></tr>
			<tr><td>
			<h2 align=\"center\" style=\"color:#0e1f5b\"> <font size=\"3\">You can send this message to no more then 10 friends.</font></h2>
			</td></tr>
			<tr><td>			
			";
		
		$select = new MultiFriendSelect();
		$select->num_rows = 3;
		$select->users_to_check = ($recipient ? 1 : 0);
		$select->page_bumper = 3;
		$select->max_select = 10;
		$select->selected_bg_image = $server."/grafics/selecterbg_selected.png";
		$select->hover_bg_image = $server.'/grafics/selecterbg_hover.png';
		if ($recipient) {
			$select->selected_uids = explode(" ",$recipient);
		}
		echo "<div style=\"border:1px solid #7f93bc;padding:10px;\">";
		echo "<form method=\"post\" action=\"sendMessage.php\">";
		echo $select->displaySelector($facebook->api_client->fql_query("SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = ".$user_id.") ORDER BY name"));
		echo "		
			<input type=\"submit\" name=\"cancel\" value=\"Cancel\" class=\"inputsubmit\" />
			<input type=\"button\" value=\"Send\" class=\"inputsubmit\" onclick='doAjax($index);' />
			</form>";
		echo "</div>";
		echo "</td></tr></table>";
		logMysqliConnectionClosed($user_id,$currentPage);
		$sqlDb->close();

?>
</br>
<font size="3">
This application participates in Unicell's contest. <a href="http://www.liveface.co.il/%D7%AA%D7%97%D7%A8%D7%95%D7%AA-%D7%90%D7%A4%D7%9C%D7%99%D7%A7%D7%A6%D7%99%D7%95%D7%AA-%D7%A4%D7%99%D7%99%D7%A1%D7%91%D7%95%D7%A7/apps/" > For rating and other applications. </a>
</font>
</html>